<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="reportCode">
              <el-input v-model="filters.reportCode" clearable placeholder="条码号"></el-input>
            </el-form-item>
            <el-form-item prop="itemName">
              <el-input v-model="filters.itemName" clearable placeholder="送检项目"></el-input>
            </el-form-item>
            <el-form-item prop="patientName">
              <el-input v-model="filters.patientName" clearable placeholder="患者姓名"></el-input>
            </el-form-item>
            <!--<el-form-item prop="date">
              <el-date-picker v-model="filters.date" :clearable="true" type="datetimerange" range-separator="至" start-placeholder="送检开始日期" end-placeholder="送检结束日期"></el-date-picker>
            </el-form-item>-->
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="listReport(filters.institutionId, filters.transferUserId)">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap_collect">
          <span>医检机构：</span>
          <el-badge v-for="tag in institutionList" :key="tag.institutionId" :value="tag.reportCount" class="item" style="margin-left: 20px">
            <el-button type="primary" size="medium" @click="listReport(tag.institutionId, null)">{{ tag.institutionName }}</el-button>
          </el-badge>
          <el-button type="mini" icon="el-icon-refresh" plain style="margin-left: 10px; margin-right: 30px" @click="handleClickRefresh">刷新</el-button>
          <!-- </div>
      </el-col>
      <el-col>
          <div class="opration_wrap_collect"> -->
          <span>收样员：</span>
          <el-badge v-for="tag in collectUserList" :key="tag.userId" :value="tag.reportCount" class="item" style="margin-left: 20px">
            <el-button type="primary" size="medium" @click="listReport(null, tag.userId)">{{ tag.userName }}</el-button>
          </el-badge>
          <el-button size="mini" icon="el-icon-refresh-left" plain type="success" style="margin-left: 10px" @click="handleClickRefreshCollect">刷新</el-button>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap_collect">
          <el-button size="mini" plain type="info" icon="el-icon-suitcase-1" v-has="permissionDelivered" @click="handleClickBatchDelivered">批量送达</el-button>
          <el-button size="mini" plain type="info" icon="el-icon-guide" v-has="permissionDelivered" @click="handleClickBatchTransfer">批量转送</el-button>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table :data="reportList" ref="reportTable" :fit="true" @selection-change="changeSelect" highlight-current-row>
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column prop="reportBeginTime" label="送检时间"></el-table-column>
        <el-table-column prop="reportCode" label="条码号"></el-table-column>
        <el-table-column prop="searchCode" label="查询号"></el-table-column>
        <el-table-column width="150px" align="center" label="姓名-性别-年龄">
          <template slot-scope="scope">
            <span>{{ scope.row.patientName }} - {{ formatSex(scope.row.patientSex) }} - {{ scope.row.patientAge }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="itemName" width="180px" label="送检项目"></el-table-column>
        <el-table-column width="200px" align="center" label="医院-科室-医生">
          <template slot-scope="scope">
            <span>{{ scope.row.hospitalName }} - {{ scope.row.officeName }} - {{ scope.row.doctorName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="institutionName" label="医检机构" width="200"></el-table-column>
        <el-table-column prop="syUserName" label="收样员" width="120"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button v-has="permissionDelivered" v-if="!filters.transferUserId" @click="handleClickDelivered(scope.$index, scope.row)" size="mini">送达</el-button>
            <el-button v-has="permissionDelivered" @click="handleClickTransfer(scope.$index, scope.row)" size="mini">转送</el-button>
            <el-button v-has="permissionBack" v-if="!filters.transferUserId" @click="handleClickReback(scope.$index, scope.row)" size="mini">撤回</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <TransferReport ref="transferReport" :rcuIdList="transferParam.rcuIdList" :cur-sy-user-id="transferParam.curSyUserId" @reloadPage="reloadPage"></TransferReport>
  </div>
</template>
<script>
import TransferReport from '@/components/TransferReport';
import * as message from '@/constants/message';
import CollectApi from '@/api/collect/collect';
import * as Constants from '@/constants/constants';
export default {
  // inject: ['reload'], //注入局部刷新
  data() {
    return {
      reportList: [],
      selectIds: [],
      filters: {
        reportCode: '',
        patientName: '',
        hospitalId: '',
        transferUserId: null,
        institutionId: null,
        itemName: '',
        reportState: '',
        state: '1',
        date: [],
      },
      transferParam: {
        rcuIdList: [],
        curSyUserId: null,
      },
      page: {
        pageNo: 1,
        pageSize: 20,
        pageTotal: 0,
      },
      institutionList: [],
      collectUserList: [],

      refreshTimer: '',
      permissionDelivered: 'SYSTEM_MANAGER_COLLECT_INS_LIST_DELIVERED',
      permissionBack: 'SYSTEM_MANAGER_COLLECT_INS_LIST_BACK',
    };
  },
  components: {
    TransferReport,
  },
  created() {
    this.init();
    this.timeToRefresh();
    window.addEventListener('keydown', this.keyDown);
  },
  mounted() {
    // 为了实现手机端下拉框可以打字搜索
    this.$Utils.removeSelectReadOnly();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      let _this = this;
      _this.listInstitution();
      _this.listCollectUser();
      _this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.listReport(this.filters.institutionId, this.filters.transferUserId);
      }
    },


    resetForm() {
      this.$refs.searchForm.resetFields();
      this.listReport(this.filters.institutionId, this.filters.transferUserId);
    },
    formatSex(cellValue) {
      if (cellValue === 1) {
        return '男';
      } else if (cellValue === 2) {
        return '女';
      }
    },
    formatReportState(cellValue) {
      if (cellValue === 0) {
        return '检测中';
      } else if (cellValue === 1) {
        return '已出结果';
      }
    },
    formatDate(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, Constants.FORMAT_DATE_YYYY_MM_DD);
    },
    formatDateTime(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, 'yyyy-MM-dd hh:mm:ss');
    },
    listInstitution() {
      let _this = this;
      CollectApi.listReportCollectInstitution({})
        .then((res) => {
          _this.institutionList = res.data;
          console.log('_this.institutionList', _this.institutionList);
        })
        .catch((error) => {
          _this.institutionList = [];
          console.error(error);
        });
    },
    listCollectUser() {
      let _this = this;
      CollectApi.listCollectTransferUsers({})
        .then((res) => {
          _this.collectUserList = res.data;
        })
        .catch((error) => {
          _this.collectUserList = [];
          console.error(error);
        });
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listReport();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listReport();
    },
    changeSelect(val) {
      this.selectIds = [];
      for (let i = 0; i < val.length; i++) {
        this.selectIds.push(val[i].rcuId);
      }
    },
    handleClickBatchDelivered() {
      let _this = this;
      if (_this.selectIds.length > 0) {
        this.$confirm('是否批量送达' + _this.selectIds.length + '个标本', message.TITLE_PROMPT, {}).then(() => {
          CollectApi.updateCollectState({ rcuIdList: _this.selectIds, updateType: 2 }).then((res) => {
            this.$notify.success({
              title: message.TITLE_SUCCESS,
              message: message.MSG_ACTION_SUCCESS,
            });
            _this.listReport(_this.filters.institutionId, _this.filters.transferUserId);
            _this.listInstitution();
          });
        });
      } else {
        this.$Utils.notifyError('请选择你要送达的标本！');
      }
    },

    handleClickDelivered(index, row) {
      let _this = this;
      this.$confirm('是否送达该标本', message.TITLE_PROMPT, {}).then(() => {
        CollectApi.updateCollectState({
          rcuIdList: [].concat(row.rcuId),
          updateType: 2,
        }).then((res) => {
          this.reportList.splice(index, 1);
          _this.listInstitution();
          _this.listReport();
          _this.handleClickRefresh();
          _this.handleClickRefreshCollect();
        });
      });
    },
    handleClickReback(index, row) {
      let _this = this;
      this.$confirm('是否撤回该标本', message.TITLE_PROMPT, {}).then(() => {
        CollectApi.updateCollectState({
          rcuIdList: [].concat(row.rcuId),
          updateType: 3,
        }).then((res) => {
          this.reportList.splice(index, 1);
          _this.listInstitution();
          _this.handleClickRefresh();
        });
      });
    },
    handleClickTransfer(index, row) {
      let _this = this;
      _this.$confirm('是否转送该标本', message.TITLE_PROMPT, {}).then(() => {
        if (_this.filters.transferUserId) {
          CollectApi.updateCollectState({ rcuIdList: [].concat(row.rcuId), updateType: 5 }).then((res) => {
            this.$notify.success({
              title: message.TITLE_SUCCESS,
              message: message.MSG_ACTION_SUCCESS,
            });
            _this.listReport(_this.filters.institutionId, _this.filters.transferUserId);
            _this.listCollectUser();
            _this.handleClickRefresh();
            _this.handleClickRefreshCollect();
          });
        } else {
          _this.transferParam.rcuIdList = [].concat(row.rcuId);
          _this.transferParam.curSyUserId = row.syUserId;
          _this.$refs.transferReport.handleCreate();
        }
      });
    },
    reloadPage() {
      this.listInstitution();
      this.listCollectUser();
      this.listReport(this.filters.institutionId, this.filters.transferUserId);
    },
    handleClickBatchTransfer() {
      let _this = this;
      if (_this.selectIds.length > 0) {
        this.$confirm('是否批量转送' + _this.selectIds.length + '个标本', message.TITLE_PROMPT, {}).then(() => {
          // 判断是否点击了收样员查询
          if (this.filters.transferUserId) {
            CollectApi.updateCollectState({ rcuIdList: _this.selectIds, updateType: 5 }).then((res) => {
              this.$notify.success({
                title: message.TITLE_SUCCESS,
                message: message.MSG_ACTION_SUCCESS,
              });
              _this.listReport(_this.filters.institutionId, _this.filters.transferUserId);
              _this.listCollectUser();
            });
          } else {
            _this.transferParam.rcuIdList = [].concat(_this.selectIds);
            _this.transferParam.curSyUserId = _this.reportList[0].userId;
            _this.$refs.transferReport.handleCreate();
          }
        });
      } else {
        this.$Utils.notifyError('请选择你要转送的标本！');
      }
    },
    handleClickRefresh() {
      this.listInstitution();
      if (this.filters.institutionId) {
        this.listReport(this.filters.institutionId, null);
      }
    },
    handleClickRefreshCollect() {
      this.listCollectUser();
      if (this.filters.transferUserId) {
        this.listReport(null, this.filters.transferUserId);
      }
    },
    listReport(institutionId, transferUserId) {
      // 只允许通过机构id/收样员id查询
      if (!institutionId && !transferUserId) {
        this.reportList = [];
        return;
      }
      let _this = this;
      if (institutionId) {
        _this.filters.institutionId = institutionId;
        _this.filters.transferUserId = null;
      }
      if (transferUserId) {
        _this.filters.transferUserId = transferUserId;
        _this.filters.institutionId = null;
      }
      let cond = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        reportCode: _this.filters.reportCode,
        patientName: _this.filters.patientName,
        itemName: _this.filters.itemName,
        institutionId: _this.filters.institutionId,
        collectFlag: 2,
      };
      CollectApi.listCollectReport(cond).then((res) => {
        _this.reportList = res.data.list;
        _this.page.pageTotal = res.data.total;
        this.selectIds = [];
        res.data.list.forEach((row) => {
          this.selectIds.push(row.rcuId);
        });
        this.$nextTick(() => {
          res.data.list.forEach((row) => {
            // 选中全部
            this.selectIds.push(row.rcuId);
            this.$refs.reportTable.toggleRowSelection(row);
          });
        });
      });
    },
    timeToRefresh() {
      this.refreshTimer = setInterval(() => {
        this.handleClickRefresh();
        this.handleClickRefreshCollect();
      }, Constants.collectRefreshTime);
    },
  },
  destroyed() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
    }
  },
};
</script>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
